package com.wisezone.workflow.core.impl;

import org.apache.commons.lang.StringUtils;

import com.wisezone.workflow.bean.WfLink;
import com.wisezone.workflow.core.Link;
import com.wisezone.workflow.core.ProcessDefinition;
import com.wisezone.workflow.exception.WfCoreException;
import com.wisezone.workflow.utils.TextUtils;

/**
 * 链接对象
 * @author tss 2009-09-05
 *
 */
public class LinkImpl  extends BasePropertyImpl implements Link{

	private WfLink wfLink;
	
	private ProcessDefinition processDefinition;
	
	/**
	 * 构造方法
	 * @param wfLink
	 * @param processDefinition
	 */
	public LinkImpl(WfLink wfLink,ProcessDefinition processDefinition) {
		this.wfLink = wfLink;
		this.processDefinition = processDefinition;
		this.setDao(processDefinition);
	}
	
	/**
	 * 条件是否合法
	 * @return
	 * @throws WfCoreException
	 */
	public boolean conditionValidate(Long processInstId) throws WfCoreException{
		
		if(processInstId == null){
			throw  new IllegalArgumentException("流程实例ID不能为空");
		}
		String condition = null;
		try {
			
			condition = this.getModel().getCondition();
			int index = condition.indexOf("#");
			while(index != -1){
				int end = condition.indexOf("}");
				String property = condition.substring(index + 2,end);
				Object obj = this.getWfVariableInstanceDao().getEntityByProcessInstId(property,processInstId).getValue();
				condition = condition.substring(0,index) + obj 
				+ condition.substring(end+1);
				index = condition.indexOf("#");
			}
		} catch (Exception e) {
			throw new WfCoreException(e);
		}
		
		try {
			if(StringUtils.isNotEmpty(condition)){
				if(log.isDebugEnabled()){
					log.debug("执行脚本: "+condition);
				}
				return TextUtils.scriptBoolean(condition);
			}
			if(log.isDebugEnabled()){
				log.debug("找不到脚本直接返回");
			}
			return true;
		} catch (Exception e) {
			throw new WfCoreException("条件脚本执行出错");
		}
		
	}
	
	
	
	public WfLink getModel() {
		return wfLink;
	}

	public void setModel(WfLink wfLink) {
		this.wfLink = wfLink;
	}
}
